﻿using BaseAPI;
using MemorySiteServer.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace MemorySiteServer.ViewModels.RoleViewModels
{
    public class RolePatchRequest:BasePatchViewModel<Role, RolePatchRequest>
    {
        /// <summary>
        /// 角色名称
        /// </summary>
        [MaxLength(20)]
        public string Name { get; set; }
        /// <summary>
        /// 权限等级，数字越低权限越高
        /// </summary>
        public int? Level { get; set; }
        /// <summary>
        /// 角色所拥有的权限
        /// </summary>
        public virtual List<RolePermission> RolePermissions { get; set; }
        private List<RolePermission> OriginalRolePermissions { get; set; }

        public void SetOriginalRolePermissions(List<RolePermission> rolePermissions)
        {
            OriginalRolePermissions = rolePermissions;
        }

        public override Role GetT()
        {
            var t = base.GetT();
            t.RolePermissions = OriginalRolePermissions;
            return t;
        }

        public override void PatchFun(Role t, DbContext dbContext)
        {
            t.Name = Name;
            if (Level != null)
                t.Level = Level.Value;
            t.RolePermissions.ForEach(x =>
            {
                if (RolePermissions.Exists(y => y.Action == x.Action))
                    dbContext.Entry(x).State = EntityState.Unchanged;
                else
                    dbContext.Entry(x).State = EntityState.Deleted;
            });
            RolePermissions.ForEach(x =>
            {
                if (!t.RolePermissions.Exists(y => y.Action == x.Action))
                    t.RolePermissions.Add(x);
            });
        }
    }
}
